import {Request} from "../../utils/request";
import func from "../../utils/functions";
import host from "../../utils/host";
const HostUrl = host.service;
const Requ = new Request();
const Func = new func();
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollData: [{
        text: '新鲜蔬菜'
      },
      {
        text: '甄选水果'
      },
      {
        text: '海鲜水产'
      },
      {
        text: '冰冻副食'
      },
      {
        text: '肉禽蛋品'
      }
    ],
    scrollLeft: 0,
    currentIndex: 0,  // 顶部导航栏
    //店铺列表
    ShopList: [{
      img: '',
      shopname: '鲜一派生鲜',
      shopscore: '4.8',
      shoppeople: '6.8',
      startmoney: '25',
      sendmoney: '1.5',
      sendtime: '30',
      km: '2.3',
      tab1: '领10元券',
      tab2: '满50减25',
      tab3: '',
    }],
    num: 3,
	latitude:0,
	longitude:0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	  this.setData({
	    navH: app.globalData.navHeight
		})
    // console.log(app.globalData.currentindex)
    // this.setData({
    //   navH: app.globalData.navHeight,
    //   currentIndex: app.globalData.currentindex == undefined ? this.data.currentIndex : app.globalData.currentindex,
    // });
    // let _this = this;
    // // 获取屏幕的总宽度
    // wx.getSystemInfo({
    //   success: function (res) {
    //     _this.setData({
    //       windowWidth: res.windowWidth
    //     });
    //   },
    // });
    // // 获取店铺列表数据
    this.GeShopList( parseInt(this.data.currentIndex) + 1);
  },

  onShow: async function(){
    // console.log(app.globalData.currentindex)
    this.setData({
      currentIndex: app.globalData.currentindex == undefined ? this.data.currentIndex : app.globalData.currentindex,
    });
	await this.getuseraddress()
	console.log('await')
	// 获取店铺列表数据
	this.GeShopList( parseInt(this.data.currentIndex) + 1);
  },

  // 获取店铺列表数据
  GeShopList: function(data){
    // 加载店铺列表
	console.log(data)
	console.log(app.globalData.openid)
	console.log(app.globalData.self_site_id)
	console.log(app.globalData.latitude)
	console.log(app.globalData.longitude)
    new Request(HostUrl.ShopList).request(
      () => {
        return {
          data: data,
          openid: app.globalData.openid,
          self_site_id: app.globalData.self_site_id,
          latitude: app.globalData.latitude,
          longitude: app.globalData.longitude,
        }
      },
      (res) => {
		  console.log(res.data)
		  // 顶部导航
		  let Tabarr = Array();
		  Tabarr.push({ 'text' : res.data.barone});
		  Tabarr.push({ 'text' : res.data.bartwo});
		  Tabarr.push({ 'text' : res.data.barthree});
		  Tabarr.push({ 'text' : res.data.barfour});
		  Tabarr.push({ 'text' : res.data.barfive});
		  this.setData({
		    scrollData: Tabarr,
		    num: Tabarr.length,
		  });
		  console.log(this.data.num)
        if(!Func.is_var(res.data, 'shops')){
          Requ.showToast('附件无店铺');
		  this.setData({
			  MS_shopList:[]
		  })
          return;
        }
        
        var shops = res.data.shops;
        var shopsH = shops.length * 221;

        let ResponseData = res.data; // 响应数据
		console.log(ResponseData)
        ResponseData['shops'].map((data, i) => {
          data['MS_name'] = data['shop_name']; // 店铺名
          data['MS_logo'] = HostUrl.HostName + data['shop_logo']; // 店铺LOGO
          data['MS_mincharge'] = data['shop_mincharge']; // 店铺起送价格
          data['MS_score'] = (data['shop_score'] * 0.01).toFixed(2); // 店铺分数
          data['MS_sendprice'] = (data['shop_sendprice'] * 0.01).toFixed(2); // 店铺派送费

          // 待后端传值
          data['MS_buypeople'] = 99; // 店铺人气数
          /* data['MS_km'] = 2.30; // 店铺人气数 */
          data['MS_tab1'] = '领10元券'; // 店铺标签
          data['MS_tab2'] = '满50减25'; // 店铺标签
          data['MS_tab3'] = '全场骨折'; // 店铺标签
        });
        this.setData({
          MS_shopList: ResponseData['shops'], // 店铺列表
          data: res.data,
          posts_key: shops,
          winHeight: shopsH,
          inputconnent: res.data.barshophot,
          // data_top: res.data.data_top,
          onpage: res.data.shop_topstate,
          shop_close: res.data.shop_close,
          currentTab: data-1,
        });
		console.log('address')
        this.distance()
      });
  },

    /**
   * 
   * @param {获取用户当前地址} e 
   */
  getuseraddress:async function(){
	  console.log('getuseraddress')
	  try{
	  	const res = await wx.getLocation({
	  	  type: 'gcj02'
	  	 });
	  	 console.log(res)
	  	 this.data.latitude = res.latitude
	  	 this.data.longitude = res.longitude
	  	 console.log('success')
	  }catch(e){
		  console.log(e)
	  	//TODO handle the exception
	  }
	 /* success:function (res) {
	 		  console.log('success')
	   
	   // const speed = res.speed
	   // const accuracy = res.accuracy
	   
	 }.bind(this),
	 fail:function(err){
	 		  console.log(err)
	 } */
  },
  /**
  * 
  * @param {计算用户与每个商铺的距离} e 
  */
  distance:function(){
	  console.log('distance')
	  this.data.MS_shopList.map(function(e,n,m){
	    e.MS_km = this.getaddreskm(e.MS_latitude,e.MS_longitude,this.data.latitude,this.data.longitude).toFixed(2);
	  }.bind(this));
	  
	  
	  this.data.MS_shopList.sort(function(a,b){
	    return a.MS_km - b.MS_km
	  })
	  this.setData({
	    MS_shopList:this.data.MS_shopList,
	  });
	  console.log(this.data.MS_shopList)
  },

    /**
   * 
   * @param {计算两个经纬度的距离 km} e 
   */
  getaddreskm:function(lat1, lng1, lat2, lng2){
    var radLat1 = lat1*Math.PI / 180.0;
    var radLat2 = lat2*Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
    s = s *6378.137 ;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s;

    
  },

  // 跳转店铺详情页面
  GoToShopDetails: function(e){
    let MS_id = e.currentTarget.dataset.msid;
    wx.navigateTo({
      url: '../new_shop/new_shop?MS_id=' + MS_id,
    })
    return;
    wx.navigateTo({
      url: '../shop_details/shop_details?MS_id=' + MS_id,
    });
  },
  // 顶部导航栏 点击事件
  switchIndexTap: function (e) {
    let curr = e.currentTarget.dataset.current;
    app.globalData.currentindex = curr
    //对索引进行处理，点击实现点击的元素位于中间，则以中间为起点
    //获取每一项的宽度
    let singleWidth = this.data.windowWidth / 5;
    this.setData({
      scrollLeft: (curr - 2) * singleWidth,
      currentTab: curr, // 修改店铺显示
    });
    console.info(this.data.scrollLeft);
    if (this.data.currentIndex == curr) {
      return false;
    } else {
      this.setData({
        currentIndex: curr
      });
    }
  },
  // 商店列表 滑动事件
  bindChange: function (e) {
    let curr = e.detail.current;
    this.GeShopList(curr+1);
    //对索引进行处理，点击实现点击的元素位于中间，则以中间为起点
    //获取每一项的宽度
    let singleWidth = this.data.windowWidth / 5;
    this.setData({
      scrollLeft: (curr - 2) * singleWidth
    });
    console.info(this.data.scrollLeft);
    if (this.data.currentIndex == curr) {
      return false;
    } else {
      this.setData({
        currentIndex: curr
      });
    }
  },

})